package com.binguo.wxapi.service;

import com.binguo.common.exception.ServiceException;
import com.binguo.common.util.SHA1;
import com.binguo.model.model.Customer;
import com.binguo.model.repository.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.binguo.common.exception.ErrorCode.TOKEN_INVALID;
import static com.binguo.common.exception.ErrorCode.WX_BUILD_TOKEN;


/**
 * Created by haibang on 18/5/20.
 */
@Service
public class WXTokenService {

    @Autowired
    CustomerRepository customerRepository;

    public String buildToken(String openId, String sessionKey){
        try {
            return SHA1.SHA1(openId + sessionKey);
        } catch (Exception e) {
            throw new ServiceException(WX_BUILD_TOKEN);
        }
    }

    public Boolean validateToken(String customerId, String token){

       Customer customer = customerRepository.findById(Integer.parseInt(customerId));
        if(!token.equals(customer.getToken())) throw new ServiceException(TOKEN_INVALID);
        return true;
    }

}
